package org.seeplnframework.skyeye.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * <p>Title: SpringUtils</p>
 * <p>Description: SpringUtils</p>
 *
 * @author wangjiawei
 * @version 1.0
 * @date 2021/9/29
 */
@Slf4j
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    public static <T> T getBean(Class<T> clazz) {

        if (context == null){
            return null;
        }
        try {
            return context.getBean(clazz);
        } catch (Exception e) {
            //ignore
            log.warn("get beanClass:{} occurs error:{}", clazz, e);
        }
        return null;
    }

    public static Object getBean(String name) {
        return getBean(name, Object.class);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        if (context == null){
            return null;
        }
        try {
            return context.getBean(name, clazz);
        } catch (Exception e) {
            //ignore
            log.warn("get beanName:{} occurs error:{}", name, e);
        }
        return null;
    }

    public static String getProperty(String name) {
        if (context == null){
            return null;
        }
        return context.getEnvironment().getProperty(name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
